package cn.edu.csust.cvs.management.support;

import com.tencentcloudapi.aai.v20180522.AaiClient;
import com.tencentcloudapi.aai.v20180522.models.TextToVoiceRequest;
import com.tencentcloudapi.aai.v20180522.models.TextToVoiceResponse;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Base64;
import java.util.UUID;
@Slf4j
@Component
public class TTSSupport {

    public String tts(String text,String filePath){
        String uuid = UUID.randomUUID().toString();
        try{
            Credential cred = new Credential("AKIDp6B3f0PCxTotiIKqnWzJNAhGiGAq2f8L", "54oKbYLr8AvRkngeNsAE4d16wYu2tV2J");
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("aai.tencentcloudapi.com");

            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            AaiClient client = new AaiClient(cred, "ap-beijing", clientProfile);

            TextToVoiceRequest req = new TextToVoiceRequest();
            req.setText(text);
            req.setSessionId(uuid);
            req.setModelType(1L);

            TextToVoiceResponse resp = client.TextToVoice(req);
            Files.write(Paths.get(filePath), Base64.getDecoder().decode(resp.getAudio()), StandardOpenOption.CREATE);
            return filePath;
        } catch (TencentCloudSDKException e) {
            log.error("text to speech failed:"+e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
